package fotel

import (
	"context"

	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
	"go.opentelemetry.io/otel/propagation"
	"go.opentelemetry.io/otel/sdk/resource"
	tracesdk "go.opentelemetry.io/otel/sdk/trace"
	semconv "go.opentelemetry.io/otel/semconv/v1.32.0"
)

var (
	isTracerInit bool // 	是否已初始otel链路追踪
)

func init() {
	// 上下文传播
	otel.SetTextMapPropagator(newPropagator())
}

func newPropagator() propagation.TextMapPropagator {
	return propagation.NewCompositeTextMapPropagator(
		propagation.TraceContext{},
		propagation.Baggage{},
	)
}

// 采用opentelemetry的方式 初始化链路追踪
func InitTracer(endpoint, serviceName string) error {
	// 创建 exporter
	exporter, err := otlptracehttp.New(context.Background(),
		otlptracehttp.WithEndpoint(endpoint),
		otlptracehttp.WithInsecure(),
	)
	if err != nil {
		return err
	}
	tp := tracesdk.NewTracerProvider(
		// 将基于父span的采样率设置为100%
		tracesdk.WithSampler(
			tracesdk.ParentBased(tracesdk.TraceIDRatioBased(1.0)),
		),
		// 始终确保在生产中批量处理
		tracesdk.WithBatcher(
			exporter,
		),
		// 在资源中记录有关此应用程序的信息
		tracesdk.WithResource(resource.NewSchemaless(
			semconv.ServiceNameKey.String(serviceName),
			attribute.String("exporter", "otlp"),
		)),
	)
	otel.SetTracerProvider(tp)
	isTracerInit = true
	return nil
}

// 获取tracer初始化状态
func GetTracerStatus() bool {
	return isTracerInit
}
